// @ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import { observer, useLocalObservable } from 'mobx-react-lite';
import Store from './store';
import './index.less';
import OrderTree from './OrderTree';
import OrderDetail from './OrderDetail';
import BatchList from './BatchList';
import ResourceDispatch from './Viewer';
import { DatePicker, Modal, Form, Spin, message, Space, Typography } from 'antd';
import { runInAction } from 'mobx';
import { getDateTime } from '@/utils';
import language from "@/locales/zh_cn";
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Text } = Typography;

export default observer(function WorkTaskDispatch() {
  const [resource, setResource] = useState<any>({});
  const store = useLocalObservable(() => new Store());
  const [form] = Form.useForm();
  const viewerRef = useRef(null);
  const isInitialized = useRef(false);
  // 预留整体缩放比例
  const [scale, setScale] = useState(1);

  // 初始化数据
  useEffect(() => {
    store.searchTree();
  }, []);

  // 处理批次订单变化
  useEffect(() => {
    if (store.searchValues?.batch_order_id) {
      if (viewerRef.current) {
        if (!isInitialized.current) {
          viewerRef.current.init();
          isInitialized.current = true;
        } else {
          viewerRef.current.reInit();
        }
      }
    }
  }, [store.searchValues?.batch_order_id]);

  const show = (resource_id: any) => {
    const resource = store.elements.find(item => item.key === resource_id);
    setResource(resource);
    form.resetFields();
    const { aps_resource_id, aps_start, aps_end } = store.taskResourceInfo || {};
    if (aps_resource_id === resource_id) {
      form.setFieldsValue({
        time: aps_start && aps_end ? [dayjs(aps_start), dayjs(aps_end)] : null
      })
    }

    runInAction(() => {
      store.visible = true;
    })
  }

  const close = () => {
    form.resetFields();
    runInAction(() => {
      store.visible = false;
    })
  }

  const onBatchOrderClick = (order) => {
    store.setSearchValues({
      batch_order_num: order['batch_order_num'],
      batch_order_id: order['id'],
      priority: Number(order['priority'])
    })
  }

  const submit = () => {
    form.validateFields().then(values => {
      const [work_start, work_end] = values.time || [];
      if (!work_start || !work_end) {
        return message.error(language.pc_begin_end_time);
      }
      const keys = ['', 'work_station_id', 'work_device_id', 'work_station_id', 'work_user_id', 'work_line_id'];
      const params = {
        work_start: work_start.format('YYYY-MM-DD HH:mm:ss'),
        work_end: work_end.format('YYYY-MM-DD HH:mm:ss'),
        [keys[store.activeBatchOrder?.capacity || 2]]: resource.resource_id,
      };
      store.dispatch(params);
    })
  }

  return (
    <div className="h-full relative">
      <div className="flex h-full gap-4 p-4 bg-gray-50">
        {/* 左侧树 */}
        <div className="w-1/6 h-full border-r bg-white rounded-lg shadow-sm flex flex-col" style={{ minWidth: '200px' }}>
          <div className="flex-1 min-h-0 overflow-auto">
            <OrderTree
              data={store.orderTree}
              actived={store.searchValues}
              total={store.orderTreeTotal}
              searchValues={store.treeSearchValues}
              loading={store.orderLoading}
              setSearchValues={store.setTreeSearchValues}
              onBatchOrderClick={onBatchOrderClick}
              searchHandle={store.searchTree}
            />
          </div>
        </div>
        {/* 中间批次列表 */}
        <div className="flex-1 h-full bg-white rounded-lg shadow-sm flex flex-col">
          <div className="flex-1 min-h-0 overflow-auto">
            <BatchList
              orderLoading={store.orderLoading}
              batchOrderList={store.batchOrderList}
              activeIndex={store.activeIndex}
              setActiveIndex={store.setActiveIndex}
            />
          </div>
        </div>
        {/* 右侧资源调度图表 */}
        {store.searchValues?.batch_order_id && (
          <div className="w-2/3 h-full border-l bg-white rounded-lg shadow-sm flex flex-col" style={{ minWidth: '300px' }}>
            {/* 只保留flex-1，不加overflow-auto */}
            <div className="flex-1 min-h-0" style={{ width: '100%' }}>
              {/* transform: scale 容器宽高100%，overflow: hidden */}
              <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left', height: '100%', overflow: 'hidden' }}>
                <ResourceDispatch
                  ref={viewerRef}
                  elements={store.elements || []}
                  links={store.links || []}
                  onResourceClick={show}
                />
              </div>
            </div>
            {/* 可选：缩放控制按钮 */}
            {/* <div className="p-2 text-right">
              <button onClick={() => setScale(s => Math.max(0.5, s - 0.1))}>-</button>
              <span style={{margin: '0 8px'}}>{(scale * 100).toFixed(0)}%</span>
              <button onClick={() => setScale(s => Math.min(2, s + 0.1))}>+</button>
            </div> */}
          </div>
        )}
      </div>
      {(store.loading || store.orderLoading) && (
        <div className="absolute inset-0 bg-white bg-opacity-50 flex items-center justify-center z-50">
          <Spin tip={language.loading} />
        </div>
      )}
      <Modal
        title="派工"
        open={store.visible}
        onCancel={close}
        onOk={submit}
        confirmLoading={store.dialogLoading}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          <Form.Item label="资源名称">
            <Text>{resource?.resource_name}</Text>
          </Form.Item>
          <Form.Item
            label="派工时间"
            name="time"
            rules={[{ required: true, message: '请选择派工时间' }]}
          >
            <RangePicker showTime />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
})
